from app.db.mongoClient import ErrMongoClient, get_mongo_client
from app.globals.uuidTool import getuuId
from . import dbSynPosUser, collectionUserRoleList
from app.settings.base import super_administrator
from app.globals.publicMethod import globalGetNowTime, globalTimeToString
from app.db.dbUserManage import getUserNameByuserId
from app.db import dbServerQuery


def queryAllRole():
    '''
    查询所有角色
    '''
    try:
        mg_client = get_mongo_client()
        res = mg_client[dbSynPosUser][collectionUserRoleList].find()
        roleList = []
        allPower = dbServerQuery.queryRolePower()
        '''
            allPower = { 
                "super_server": { 
                    "name": "学校信息",
                    "desc": "修改学校信息...",
                    "power": ["server_manage", "server_query"]
                },
                "super_dining": {
                    "name": "餐厅管理",
                    "desc": "管理餐厅创建、删除、编辑...",
                    "power": ["dining_manage", "dining_query"]
                }
            }
        '''
        for v in res:
            roleName = v.get('roleName')
            if roleName == super_administrator:
                continue

            rolePower = {}
            resRolePower = v.get('rolePower')
            # resRolePower = ["super_server", "super_dining", "super_stall", "super_user", "order_stats"]
            if resRolePower is not None and allPower is not None:
                for key in resRolePower:
                    if key is not None and len(key) > 0:
                        rolePower[key] = allPower[key]

            role = {
                'roleId': v.get('roleId'),
                'roleName': roleName,
                'createTime': globalTimeToString(v.get('createTime')),
                'updateTime': globalTimeToString(v.get('updateTime')),
                'creatorName': v.get('creatorName'),
                'modifierName': v.get('modifierName'),
                'roleDesc': v.get('roleDesc'),
                'rolePower': rolePower
            }
            roleList.append(role)

        return roleList
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def createRole(roleName, rolePower, roleDesc, userId):
    '''
    创建角色
    '''
    try:
        mg_client = get_mongo_client()
        cond = {'roleName': roleName}
        collection = mg_client[dbSynPosUser][collectionUserRoleList]
        res = collection.find_one(cond)
        roleId = getuuId()
        # 如果该角色已存在
        if res is not None:
            return None

        now = globalGetNowTime()
        username = getUserNameByuserId(userId)
        data = {
            'roleId': roleId,
            'roleName': roleName,
            'createTime': now,
            'updateTime': now,
            'creatorName': username,
            'modifierName': username,
            'roleDesc': roleDesc,
            'rolePower': rolePower
        }
        collection.insert_one(data)
        return roleId
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def editRole(roleId, roleName, rolePower, roleDesc):
    '''
    编辑角色
    '''
    try:
        mg_client = get_mongo_client()
        cond = {'roleId': roleId}
        collection = mg_client[dbSynPosUser][collectionUserRoleList]
        #超级管理员角色不让编辑
        if roleName == super_administrator:
            return False

        res = collection.find_one(cond)
        if res is not None:
            if res['roleName'] == super_administrator:
                return False

        return collection.find_one_and_update(
            cond, {
                '$set': {
                    'roleName': roleName,
                    'rolePower': rolePower,
                    'roleDesc': roleDesc
                }
            })
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def delRole(roleId):
    '''
    删除角色
    '''
    try:
        mg_client = get_mongo_client()
        cond = {'roleId': roleId}
        collection = mg_client[dbSynPosUser][collectionUserRoleList]
        # 超级管理员角色不让删除
        res = collection.find_one(cond)
        if res is not None:
            if res['roleName'] == super_administrator:
                return False

        return collection.find_one_and_delete(cond)
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def getRoleNameById(roleId):
    '''
    根据角色Id获取角色名
    '''
    try:
        mg_client = get_mongo_client()
        cond = {'roleId': roleId}
        collection = mg_client[dbSynPosUser][collectionUserRoleList]
        res = collection.find_one(cond)
        if res is not None:
            return res.get('roleName')

    except Exception as e:
        raise ErrMongoClient.data(str(e))
